//
//  PLRLobbyViewController.m
//  PLRLiveShow
//
//  Created by 赵小燕 on 2017/8/5.
//  Copyright © 2017年 xiaoyanzhao. All rights reserved.
//

#import "PLRLobbyViewController.h"
#import "PLRBroadcastRoomViewController.h"
#import "PlcPlayerViewController.h"
#import "PlcRoomInfo.h"

static NSString * const cellIdentifier = @"KTableViewCellIdentifier";
static NSString * const kHost = @"http://192.168.1.200:9000/rooms";

@interface PLRLobbyViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray<PlcRoomInfo *> *roomInfo;

@end

@implementation PLRLobbyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.roomInfo = [[NSMutableArray<PlcRoomInfo *> alloc] init];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
    self.navigationItem.titleView = ({
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = @"大厅";
        [titleLabel sizeToFit];
        titleLabel;
    });
    
    self.navigationItem.rightBarButtonItem = ({
        UIBarButtonItem *button = [[UIBarButtonItem alloc] init];
        button.title = @"直播";
        button.target = self;
        button.action = @selector(_onPressedBeginBroadcastButton:);
        button;
    });
    
    self.navigationItem.leftBarButtonItem = ({
        UIBarButtonItem *button = [[UIBarButtonItem alloc] init];
        button.title = @"刷新";
        button.target = self;
        button.action = @selector(_onPressedRefreshLobbyListButton:);
        button;
    });

    [self _refreshLobbyListWithComplete:nil];
}

- (void)_onPressedRefreshLobbyListButton:(UIBarButtonItem *)button {
    button.enabled = NO;
    
    [self _refreshLobbyListWithComplete:^{
        button.enabled = YES;
    }];
}

- (void)_onPressedBeginBroadcastButton:(id)sender {
    PLRBroadcastRoomViewController *vc = [[PLRBroadcastRoomViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_refreshLobbyListWithComplete:(void(^)())complete {
    NSString *url = [NSString stringWithFormat:@"%@", kHost];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 10;
    
    [request addValue:@"livetv" forHTTPHeaderField:@"author"];
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error != nil || response == nil || data == nil) {
            NSLog(@"获取大厅列表失败... %@", error);
        }
        NSDictionary *roomsDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"1111 %@", roomsDic);
        NSMutableArray *roomsArray = [roomsDic objectForKey:@"data"];
        self.roomInfo = ({
            NSMutableArray<PlcRoomInfo *> *roomInfos = [[NSMutableArray<PlcRoomInfo *> alloc] init];
            for (NSUInteger i = 0; i < roomsArray.count; i++) {
                NSDictionary *room = roomsArray[i];
                NSMutableDictionary *roomDic = [room objectForKey:@"room"];
                NSMutableDictionary *broadcastDic = [room objectForKey:@"broadcaster"];
                
                PlcRoomInfo *roomInfo = [[PlcRoomInfo alloc] init];
                roomInfo.roomName = roomDic[@"name"];
                roomInfo.playURL = roomDic[@"playUrl"];
                roomInfo.roomID = [roomDic[@"id"] integerValue];
                roomInfo.roomNO = roomDic[@"no"];
                roomInfo.broadcastName = broadcastDic[@"name"];
                roomInfo.imageURL = roomDic[@"snapPic"];
                roomInfo.broadcastID = [broadcastDic[@"id"] integerValue];
                roomInfo.broadcastSex = [broadcastDic[@"sex"] integerValue];
                [roomInfos addObject:roomInfo];
            }
            roomInfos;
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            if (complete) {
                complete();
            }
        });
    }];
    [task resume];
                                  
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PlcRoomInfo *roomInfo = [self.roomInfo objectAtIndex:indexPath.row];
    PlcPlayerViewController *vc = [[PlcPlayerViewController alloc] initWithRoomInfo:roomInfo];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.roomInfo.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    PlcRoomInfo *roomInfo = [self.roomInfo objectAtIndex:indexPath.row];
    cell.textLabel.text = roomInfo.roomName;
    
    NSURL *url = [NSURL URLWithString:roomInfo.imageURL];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    cell.imageView.image = image;
//    cell.detailTextLabel.text = roomInfo.roomName;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}




@end
